package org.keyboardman.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.keyboardman.model.Resource;
import org.keyboardman.model.User;
import org.keyboardman.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.apache.commons.lang.SystemUtils.USER_NAME;

/**
 * Created by longky on 2017/3/21.
 */
public class OneRealM extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) principalCollection.fromRealm(getName()).iterator().next();
        List<Resource> list=  userService.getResourcebyUserName(userName);

        Set<String> roleNames = new HashSet<String>();
        Set<String> permissions = new HashSet<String>();
        for(Resource re : list){
            permissions.add(re.getUrl());
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.getUserbyUserName(token.getUsername());

        if (user != null) {
//            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); 加密方式待研究一下
            if (user.getStatus()!=0) {
                // 抛出 帐号锁定异常
                throw new LockedAccountException();
            }
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
//            return new SimpleAccount(user.getUsername(), user.getPassword(), getName());
        } else {
            throw new UnknownAccountException();
        }

    }
}
